<template>
  <div class="product-container">
    <!-- 统一居中容器 -->
    <div class="main-content">
      <!-- 分类导航 -->
      <div class="category-bar">
        <span class="category-label">分类:</span>
        <span
            v-if="queryType === 'search'"
            :class="{ active: currentCategory === 'all' }"
            @click="handleCategoryClick('all')"
        >
          全部
        </span>
        <template v-if="Array.isArray(categoryList)">
          <span
              v-for="(category, index) in categoryList"
              :key="index"
              :class="{ active: currentCategory === category.id }"
              @click="handleCategoryClick(category.id)"
          >
            {{ category.categoryName }}
          </span>
        </template>
        <template v-else-if="categoryList">
          <span
              :class="{ active: currentCategory === categoryList.id }"
              @click="handleCategoryClick(categoryList.id)"
          >
            {{ categoryList.categoryName }}
          </span>
        </template>
      </div>

      <!-- 排序选项 -->
      <div class="sort-tab">
        <span
            v-for="(sort, index) in sortTypes"
            :key="index"
            :class="{ active: currentSort === sort.value }"
            @click="handleSortChange(sort.value)"
        >
          {{ sort.label }}
          <!-- 为价格排序添加方向指示器 -->
          <i v-if="sort.value === 'price' && currentSort === 'price'"
             :class="['price-direction', priceDirection === 1 ? 'asc' : 'desc']"></i>
        </span>
      </div>

      <!-- 商品列表 -->
      <div class="product-grid">
        <template v-if="Array.isArray(categoryList)">
          <div v-for="(product, index) in categoryList.reduce((acc, cat) => acc.concat(cat.goodsList || []), [])" :key="index" class="product-item">
            <img :src="baseUrl + product.coverImage" alt="商品图" class="product-image">
            <p class="product-name">{{ product.goodsName }}</p>
            <div class="price-info">
              <span class="current-price">{{ product.salePrice }}元</span>
              <span v-if="product.originalPrice" class="original-price">{{ product.originalPrice }}元</span>
            </div>
          </div>
        </template>
        <template v-else-if="categoryList?.goodsList">
          <div v-for="(product, index) in categoryList.goodsList" :key="index" class="product-item">
            <img :src="baseUrl + product.coverImage" alt="商品图" class="product-image">
            <p class="product-name">{{ product.goodsName }}</p>
            <div class="price-info">
              <span class="current-price">{{ product.salePrice }}元</span>
              <span v-if="product.originalPrice" class="original-price">{{ product.originalPrice }}元</span>
            </div>
          </div>
        </template>
      </div>

      <!-- 无数据提示 -->
      <div v-if="!categoryList || (Array.isArray(categoryList) && categoryList.every(cat => (cat.goodsList || []).length === 0)) || (!Array.isArray(categoryList) && (categoryList.goodsList || []).length === 0)" class="no-data">
        暂无相关商品
      </div>
    </div>
  </div>
</template>

<script>
import { getBaseUrl, sendRequest } from "@/util/request";

export default {
  data() {
    return {
      baseUrl: getBaseUrl(),
      // 查询类型：category(分类查询) 或 search(搜索查询)
      queryType: 'category',
      // 分类ID或搜索关键词
      queryValue: '',
      // 分类列表
      categoryList: [],
      currentCategory: 'all',

      // 排序类型
      sortTypes: [
        { value: 'default', label: '综合' },
        { value: 'sales', label: '销量' },
        { value: 'price', label: '价格' }
      ],
      currentSort: 'default',
      // 价格排序方向：1升序，-1降序
      priceDirection: 1,
    };
  },
  computed: {

    // 根据排序条件处理商品列表
    sortedProductList() {
      let allGoods = [];
      if (Array.isArray(this.categoryList)) {
        allGoods = this.categoryList.reduce((acc, cat) => {
          return acc.concat(cat.goodsList || []);
        }, []);
      } else if (this.categoryList && this.categoryList.goodsList) {
        allGoods = this.categoryList.goodsList;
      }

      if (!allGoods.length) return [];

      // 创建商品列表的副本，避免修改原始数据
      let sortedList = [...allGoods];

      // 根据排序类型进行排序
      switch (this.currentSort) {
        case 'default':
          // 综合排序 - 按时间排序，这里假设有一个时间字段，如果没有则保持原顺序
          sortedList.sort((a, b) => {
            if (a.createTime && b.createTime) {
              return new Date(b.createTime) - new Date(a.createTime);
            }
            return 0;
          });
          break;
        case 'sales':
          // 销量排序
          sortedList.sort((a, b) => {
            const salesA = parseInt(a.sales || 0);
            const salesB = parseInt(b.sales || 0);
            return salesB - salesA;
          });
          break;
        case 'price':
          // 价格排序
          sortedList.sort((a, b) => {
            // 提取价格数字部分
            const priceA = parseFloat(a.salePrice);
            const priceB = parseFloat(b.salePrice);
            // 根据排序方向决定升序或降序
            return this.priceDirection === 1 ? priceA - priceB : priceB - priceA;
          });
          break;
      }

      // 如果是分类查询，过滤出当前分类的商品
      if (this.queryType === 'category' && this.currentCategory !== 'all') {
        return sortedList.filter(item => item.categoryId === this.currentCategory);
      }

      // 如果是搜索查询且选择了特定分类
      if (this.queryType === 'search' && this.currentCategory !== 'all') {
        return sortedList.filter(item => item.categoryId === this.currentCategory);
      }

      return sortedList;
    }
  },
  created() {
    // 从路由参数中获取查询类型和值
    this.initQueryParams();
    // 获取分类列表和关联的商品信息
    this.fetchCategories();
  },
  methods: {
    // 初始化查询参数
    initQueryParams() {
      // 从路由中获取查询类型和值
      if (this.$route.query.type === 'search') {
        // 搜索查询
        this.queryType = 'search';
        this.queryValue = this.$route.query.keyword || '';
        this.currentCategory = this.queryValue;
      } else {
        // 分类查询
        this.queryType = 'category';
        this.queryValue = this.$route.params.id || '';
        this.currentCategory = this.queryValue;
      }
    },

    // 获取分类列表
    async fetchCategories() {
      try {
        let url;
        let requestBody;
        if (this.queryType === 'search') {
          url = `index/category/selectLikeGoodsCategory?keyword=${encodeURIComponent(this.currentCategory)}`;
          requestBody = this.currentCategory;
        } else {
          // 确保分类 ID 是整数类型
          const categoryId = parseInt(this.currentCategory);
          if (isNaN(categoryId)) {
            console.error('分类 ID 不是有效的整数');
            return;
          }
          url = `index/category/selectGoodsCategoryId/${categoryId}`;
        }
        const res = await sendRequest("post", url, requestBody);
        if (res && res.categoryDto) {
          this.categoryList = res.categoryDto;
        }
        if (res && res.goodsLike) {
          this.categoryList = res.goodsLike;
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
      }
    },
    // 处理分类点击
    handleCategoryClick(categoryId) {
      this.currentCategory = categoryId;
      if (categoryId === 'all' && this.queryType === 'search') {
        // 点击全部且为搜索查询时，使用地址栏的搜索关键词
        this.currentCategory = this.$route.query.keyword || '';
        this.queryType = 'search';
      } else {
        this.queryType = 'category';
      }
      // 如果是分类查询模式且点击了不同的分类，则更新路由
      if (this.queryType === 'category' && categoryId!== this.$route.params.id) {
        this.$router.push({
          path: `/index/goodsCategory/${categoryId}`
        });
      }
      this.fetchCategories();
    },

    // 处理排序变更
    handleSortChange(sort) {
      if (sort === 'price' && this.currentSort === 'price') {
        // 如果已经是价格排序，则切换升降序
        this.priceDirection *= -1;
      } else {
        this.currentSort = sort;
        // 重置价格排序方向
        if (sort === 'price') {
          this.priceDirection = 1;
        }
      }

      // 注意：不需要重新获取商品列表，因为我们使用计算属性来过滤和排序
    }
  },
  watch: {
    // 监听路由变化，重新获取数据
    '$route'(to, from) {
      if (to.path !== from.path || to.query.keyword !== from.query.keyword) {
        this.initQueryParams();
        this.fetchCategories();
      }
    }
  }
};
</script>

<style scoped>
/* 简单的重置样式示例 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.product-container {
  padding: 20px;
  background-color: #f9f9f9;
}

/* 统一居中容器 */
.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

/* 分类导航样式 */
.category-bar {
  margin-bottom: 20px;
  font-size: 16px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 100%; /* 确保不超出父容器宽度 */
}

.sort-tab {
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  max-width: 100%; /* 确保不超出父容器宽度 */
}

.category-bar .category-label {
  color: #666;
  margin-right: 10px;
  font-weight: bold;
}

.category-bar span:not(.category-label) {
  margin-right: 20px;
  cursor: pointer;
  color: #666;
  padding: 5px 10px;
  border-radius: 15px;
  transition: all 0.3s;
}

.category-bar span.active {
  color: #ff6700;
  background: #fff2e8;
  font-weight: bold;
}

.category-bar span:not(.category-label):hover {
  color: #ff6700;
}

/* 排序选项样式 */
.sort-tab {
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
}

.sort-tab span {
  margin-right: 20px;
  cursor: pointer;
  color: #666;
  padding: 5px 15px;
  border-radius: 15px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
}

.sort-tab span.active {
  color: #ff6700;
  background: #fff2e8;
  font-weight: bold;
}

.sort-tab span:hover {
  color: #ff6700;
}

/* 价格排序方向指示器 */
.price-direction {
  display: inline-block;
  width: 0;
  height: 0;
  margin-left: 5px;
  position: relative;
}

.price-direction.asc::before,
.price-direction.desc::before {
  content: "";
  position: absolute;
  left: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
}

.price-direction.asc::before {
  bottom: -2px;
  border-bottom: 6px solid #ff6700;
}

.price-direction.desc::before {
  top: -2px;
  border-top: 6px solid #ff6700;
}

/* 商品列表样式 */
.product-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: auto;
  gap: 20px;
}

/* 无数据提示 */
.no-data {
  text-align: center;
  padding: 50px 0;
  color: #999;
  font-size: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 992px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: 1fr;
  }

  .category-bar {
    flex-direction: column;
    align-items: flex-start;
  }

  .category-bar span {
    margin: 5px 0;
  }

  .sort-tab {
    flex-wrap: wrap;
  }
}

.product-item {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
  /* 可以根据需要设置固定高度 */
  height: 350px;
}
.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  margin-bottom: 15px;
  max-width: 100%;
  max-height: 200px;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 10px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 最多显示2行 */
  -webkit-box-orient: vertical;
  line-height: 20px; /* 调整行高 */
}

.price-info {
  margin-bottom: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 12px;
  margin-left: 5px;
}

.current-price {
  color: #ff6700;
  font-size: 16px;
  font-weight: bold;
}

.discount-tag {
  display: inline-block;
  font-size: 12px;
  color: #ff6700;
  background-color: #fff2e8;
  padding: 2px 8px;
  border-radius: 4px;
  margin-top: 5px;
}
</style>
